﻿@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>测试WebUploader上传功能</title>
    <link href="~/Content/webuploader/webuploader.css" rel="stylesheet" />
    <link href="~/Content/webuploader/uploadImage.css" rel="stylesheet" />
</head>
<body>
    <div id="webuploader" class="uploader">
        @*<div class="queueList">
            <ul class="filelist">
                <li id="WU_FILE_1">
                    <p class="title">1.jpg</p>
                    <p class="imgWrap">
                        <img src="">
                    </p>
                    <p class="cancel">
                        删除
                    </p>
                    <p class="error">上传失败，请重试</p>
                </li>
                <li id="WU_FILE_2"><p class="title">2.jpg</p><p class="imgWrap"><img src=""></p><p class="progress"><span></span></p><div class="file-panel" style="height: 0px;"><span class="cancel">删除</span><span class="rotateRight">向右旋转</span><span class="rotateLeft">向左旋转</span></div></li>
            </ul>
        </div>
        <div class="statusBar">
            <div class="progress">
                <span class="text">0%</span>
                <span class="percentage"></span>
            </div>
            <div class="info"></div>
            <div class="btns">
                <div class="uploadBtn" id="filePicker">选择图片</div><div class="uploadBtn">开始上传</div>
            </div>
        </div>*@
    </div>
    <script src="~/Content/webuploader/jquery-2.2.3.min.js"></script>
    <script src="~/Content/webuploader/webuploader.min.js"></script>
    <script>
        $(function () {
            var imgUploder = new ImageUploder("webuploader");
            //alert(imgUploder.responseData);
            //alert($("#webuploader").data("responseData"));
        });
        (function ($) {
            var ImageUploder = function (domId, setting) {
                var _self = this;
                //设置默认参数
                this.setting = {
                    pick: {
                        id: '#filePicker',
                        multiple: false,
                    }
                    , formData: {}
                    , server: "/TestUpload/UpLoadProcess"
                    , method: "POST"
                    , resize: false// 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                    , accept: {
                        title: 'Images',
                        extensions: 'gif,jpg,jpeg,bmp,png',
                        mimeTypes: 'image/*'
                    }
                    , fileNumLimit: 10                         // 验证文件总数量, 超出则不允许加入队列。
                    , fileSizeLimit: 50 * 1024 * 1024           //50M //验证文件总大小是否超出限制, 超出则不允许加入队列
                    , fileSingleSizeLimit: 10 * 1024 * 1024    //10M //验证单个文件大小是否超出限制, 超出则不允许加入队列。
                };
                $.extend(this.setting, setting);

                var $webuploader = $("#" + domId),
                    // 优化retina, 在retina下这个值是2
                    ratio = window.devicePixelRatio || 1,
                    // 缩略图大小
                    thumbnailWidth = 110 * ratio,
                    thumbnailHeight = 110 * ratio,
                    // 所有文件的进度信息，key为file id
                    percentages = {},
                    fileCount = 0, fileSize = 0,
                    // 可能有pedding, ready, uploading, confirm, done.
                    state = 'pedding',
                    responseData=[],
                // 图片容器
                $queue = $('<ul class="filelist"></ul>')
                    .appendTo($webuploader),
                    $statusBar = $('<div class="statusBar">' +
                            '<div class="progress">' +
                            '<span class="text">0%</span>' +
                            '<span class="percentage"></span>' +
                            '</div>' +
                            '<div class="info"></div>' +
                            '<div class="btns">' +
                            '<div class="uploadBtn">开始上传</div><div id="filePicker" class="chooseImg">选择图片</div>' +
                            '</div></div>')
                    .appendTo($webuploader),
                    //提示信息
                    $tipInfo = $statusBar.find(".info");
                $progress = $statusBar.find('.progress').hide(),
                //上传按钮
                $upload = $statusBar.find('.uploadBtn');
                var uploader = WebUploader.create(this.setting);

                // 当有文件添加进来时执行，负责view的创建
                function addFile(file) {
                    var $li = $('<li id="' + file.id + '">' +
                        '<p class="title" style="display:none;">' + file.name + '</p>' +
                        '<p class="imgWrap"></p>' +
                        '<p class="progress"><span></span></p>'+
                        '<p class="cancel">删除</p></li>'),
                        $wrap = $li.find('p.imgWrap'),
                        $info = $('<p class="error"></p>'),
                        $cancle = $li.find('.cancel').hide(),
                        showError = function (code) {
                            switch (code) {
                                case 'exceed_size':
                                    text = '文件大小超出';
                                    break;

                                case 'interrupt':
                                    text = '上传暂停';
                                    break;

                                default:
                                    text = '上传失败，请重试';
                                    break;
                            }

                            $info.text(text).appendTo($li).show();
                        };

                    if (file.getStatus() === 'invalid') {
                        showError(file.statusText);
                    } else {
                        // lazyload
                        $wrap.text('预览中');
                        uploader.makeThumb(file, function (error, src) {
                            var img;
                            if (error) {
                                $wrap.text('不能预览');
                                return;
                            }
                            img = $('<img src="' + src + '">');
                            $wrap.empty().append(img);
                        }, thumbnailWidth, thumbnailHeight);

                        percentages[file.id] = [file.size, 0];
                        file.rotation = 0;
                    }
                    $li.on('mouseenter', function () {
                        $cancle.fadeIn();
                    });

                    $li.on('mouseleave', function () {
                        $cancle.fadeOut();
                    });
                    $cancle.on('click', function () {
                        uploader.removeFile(file);
                        removeFile(file);
                    });

                    $li.appendTo($queue);
                }

                // 负责view的销毁
                function removeFile(file) {
                    var $li = $('#' + file.id);

                    delete percentages[file.id];
                    updateTotalProgress();
                    $li.off().remove();
                }
                function updateTotalProgress() {
                    var loaded = 0,
                        total = 0,
                        spans = $progress.children(),
                        percent;
                    $.each(percentages, function (k, v) {
                        total += v[0];
                        loaded += v[0] * v[1];
                    });
                    percent = total ? loaded / total : 0;
                    spans.eq(0).text(Math.round(percent * 100) + '%');
                    spans.eq(1).css('width', Math.round(percent * 100) + '%');
                    updateStatus();
                }

                function updateStatus() {
                    var text = '', stats;

                    if (state === 'ready') {
                        text = '选中' + fileCount + '张图片，共' +
                                WebUploader.formatSize(fileSize) + '。';
                    } else if (state === 'confirm') {
                        stats = uploader.getStats();
                        if (stats.uploadFailNum) {
                            text = '已成功上传' + stats.successNum + '张照片至XX相册，' +
                                stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片'
                        }

                    } else {
                        stats = uploader.getStats();
                        text = '共' + fileCount + '张（' +
                                WebUploader.formatSize(fileSize) +
                                '），已上传' + stats.successNum + '张';

                        if (stats.uploadFailNum) {
                            text += '，失败' + stats.uploadFailNum + '张';
                        }
                    }

                    $tipInfo.html(text);
                }

                function setState(val) {
                    var file, stats;
                    if (val === state) {
                        return;
                    }
                    //$upload.removeClass('state-' + state);
                    //$upload.addClass('state-' + val);
                    state = val;
                    switch (state) {
                        case 'pedding':
                            $queue.hide();
                            $statusBar.addClass('element-invisible');
                            uploader.refresh();
                            break;

                        case 'ready':
                            $queue.show();
                            $statusBar.removeClass('element-invisible');
                            uploader.refresh();
                            break;

                        case 'uploading':
                            $progress.show();
                            $upload.text('暂停上传');
                            break;

                        case 'paused':
                            $progress.show();
                            $upload.text('继续上传');
                            break;

                        case 'confirm':
                            $progress.hide();
                            $upload.text('开始上传');

                            stats = uploader.getStats();
                            if (stats.successNum && !stats.uploadFailNum) {
                                setState('finish');
                                return;
                            }
                            break;
                        case 'finish':
                            stats = uploader.getStats();
                            if (stats.successNum) {
                                $tipInfo.html('上传成功');
                            } else {
                                // 没有成功的图片，重设
                                state = 'done';
                                location.reload();
                            }
                            break;
                    }
                    updateStatus();
                }

                uploader.onUploadProgress = function (file, percentage) {
                    var $li = $('#' + file.id),
                        $percent = $li.find('.progress span');

                    $percent.css('width', percentage * 100 + '%');
                    percentages[file.id][1] = percentage;
                    updateTotalProgress();
                };

                uploader.onFileQueued = function (file) {
                    fileCount++;
                    fileSize += file.size;

                    addFile(file);
                    setState('ready');
                    updateTotalProgress();
                };

                uploader.onFileDequeued = function (file) {
                    fileCount--;
                    fileSize -= file.size;
                    if (!fileCount) {
                        setState('pedding');
                    }
                    removeFile(file);
                    updateTotalProgress();

                };
                uploader.on("uploadSuccess", function (file, response) {
                    responseData.push(response);
                });
                uploader.on("uploadComplete", function (file) {
                    $webuploader.data("responseData", responseData);
                });
                uploader.on('all', function (type) {
                    var stats;
                    switch (type) {
                        case 'uploadFinished':
                            setState('confirm');
                            break;

                        case 'startUpload':
                            setState('uploading');
                            break;

                        case 'stopUpload':
                            setState('paused');
                            break;

                    }
                });

                uploader.onError = function (code) {
                    if (code == "F_DUPLICATE") {
                        $tipInfo.html('Eroor: 文件已存在');
                    } else if (code == "F_EXCEED_SIZE") {
                        $tipInfo.html('Eroor: 单个文件大小超过限制，最大为' + _self.setting.fileSingleSizeLimit/(1024*1024)+"M");
                    } else if (code == "Q_EXCEED_NUM_LIMIT") {
                        $tipInfo.html('Eroor: 文件总数最大为' + _self.setting.fileNumLimit);
                    } else if (code == "Q_EXCEED_SIZE_LIMIT") {
                        $tipInfo.html('Eroor: 文件总大小超过限制，最大为' + _self.setting.fileSizeLimit / (1024 * 1024) + "M");
                    } else {
                        $tipInfo.html('Eroor: ' + code);
                    }
                };

                $upload.on('click', function () {
                    if ($(this).hasClass('disabled')) {
                        return false;
                    }
                    if (state === 'ready') {
                        uploader.upload();
                    } else if (state === 'paused') {
                        uploader.upload();
                    } else if (state === 'uploading') {
                        uploader.stop();
                    }
                });
                $tipInfo.on('click', '.retry', function () {
                    uploader.retry();
                });
            }
            window["ImageUploder"] = ImageUploder;
        })(jQuery);

    </script>
</body>
</html>
